package com.ruoyi.sts.service.impl;

import java.util.Collections;
import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.sts.domain.*;
import com.ruoyi.sts.service.IStsDeviceService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import com.ruoyi.sts.mapper.StsDataDetailMapper;
import com.ruoyi.sts.service.IStsDataDetailService;
import com.ruoyi.common.core.text.Convert;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * 客流数据Service业务层处理
 * 
 * @author maoxiaodong
 * @date 2025-04-20
 */
@Service
public class StsDataDetailServiceImpl implements IStsDataDetailService 
{
    @Autowired
    private StsDataDetailMapper stsDataDetailMapper;

    @Autowired
    private IStsDeviceService stsDeviceService;

    /**
     * 查询客流数据
     * 
     * @param id 客流数据主键
     * @return 客流数据
     */
    @Override
    public StsDataDetail selectStsDataDetailById(Long id)
    {
        return stsDataDetailMapper.selectStsDataDetailById(id);
    }

    /**
     * 查询客流数据列表
     * 
     * @param stsDataDetail 客流数据
     * @return 客流数据
     */
    @Override
    public List<StsDataDetail> selectStsDataDetailList(StsDataDetail stsDataDetail)
    {
        return stsDataDetailMapper.selectStsDataDetailList(stsDataDetail);
    }

    /**
     * 新增客流数据
     * 
     * @param stsDataDetail 客流数据
     * @return 结果
     */
    @Override
    @Transactional
    public int insertStsDataDetail(StsDataDetail stsDataDetail)
    {
        return stsDataDetailMapper.insertStsDataDetail(stsDataDetail);
    }

    /**
     * 修改客流数据
     * 
     * @param stsDataDetail 客流数据
     * @return 结果
     */
    @Override
    @Transactional
    public int updateStsDataDetail(StsDataDetail stsDataDetail)
    {
        return stsDataDetailMapper.updateStsDataDetail(stsDataDetail);
    }

    @Override
    public int updateStsDataDetailNum(StsDataDetail addStsDataDetail) {
        if(addStsDataDetail.getDeptId3() == null){
            throw  new RuntimeException("区域不能为空。");
        }
        if(addStsDataDetail.getStartTime() == null){
            throw  new RuntimeException("更新时间不能为空。");
        }
        Date date = DateUtils.dateTime("yyyy-MM-dd HH", DateUtils.parseDateToStr("yyyy-MM-dd HH", addStsDataDetail.getStartTime()));


        StsDevice stsDevice = stsDeviceService.selectStsDeviceByDeptId3(addStsDataDetail.getDeptId3());
        if(stsDevice == null){
            throw  new RuntimeException("该区域没有维护设备，请维护后再更新。");
        }
        StsDataDetail stsDataDetail = stsDataDetailMapper.lockByDate(stsDevice.getId(), date);
        if(stsDataDetail == null){
            stsDataDetail = new StsDataDetail();
        }
        /** 开始时间 */
        stsDataDetail.setStartTime(date);
        /** 结束时间 */
        stsDataDetail.setEndTime(DateUtils.addHours(date, 1));

        stsDataDetail.setDeviceId(stsDevice.getId());
        stsDataDetail.setDeviceName(stsDevice.getName());
        stsDataDetail.setDeptId1(stsDevice.getDeptId1());
        /** 一级部门名称 */
        stsDataDetail.setDeptName1(stsDevice.getDeptName1());
        /** 二级部门ID */
        stsDataDetail.setDeptId2(stsDevice.getDeptId2());
        /** 二级部门名称 */
        stsDataDetail.setDeptName2(stsDevice.getDeptName2());
        /** 三级部门ID */
        stsDataDetail.setDeptId3(stsDevice.getDeptId3());
        /** 三级部门名称 */
        stsDataDetail.setDeptName3(stsDevice.getDeptName3());

        /** 经过人数 */
        stsDataDetail.setPassNum(numAdd(addStsDataDetail.getPassNum(),stsDataDetail.getPassNum()));
        /** 进入人数 */
        stsDataDetail.setInNum(numAdd(addStsDataDetail.getInNum(),stsDataDetail.getInNum()));
        /** 离开人数 */
        stsDataDetail.setOutNum(numAdd(addStsDataDetail.getOutNum(),stsDataDetail.getOutNum()));
        /** 重复人数 */
        stsDataDetail.setRepNum(numAdd(addStsDataDetail.getRepNum(),stsDataDetail.getRepNum()));
        if(stsDataDetail.getId() != null){
            stsDataDetailMapper.updateStsDataDetail(stsDataDetail);
        }else{
            stsDataDetailMapper.insertStsDataDetail(stsDataDetail);
        }

        return 1;
    }

    /**
     * 批量删除客流数据
     * 
     * @param ids 需要删除的客流数据主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStsDataDetailByIds(String ids)
    {
        return stsDataDetailMapper.deleteStsDataDetailByIds(Convert.toStrArray(ids));
    }

    /**
     * 删除客流数据信息
     * 
     * @param id 客流数据主键
     * @return 结果
     */
    @Override
    @Transactional
    public int deleteStsDataDetailById(Long id)
    {
        return stsDataDetailMapper.deleteStsDataDetailById(id);
    }

    @Override
    public List<StsDataDetail> selectStsDataStatisticList(StsDataStatisticQuery stsDataStatisticQuery) {
        return stsDataDetailMapper.selectStsDataStatisticList(stsDataStatisticQuery);
    }

    @Override
    public List<StsDataDetail> selectStsDataDeptStatisticList(StsDataDeptStatisticQuery stsDataDeptStatisticQuery) {
        return stsDataDetailMapper.selectStsDataDeptStatisticList(stsDataDeptStatisticQuery);
    }

    @Override
    public List<StsDataDetail> selectStsDataDeptStatisticTop10List(StsDataDeptStatisticQuery stsDataDeptStatisticQuery) {
        return stsDataDetailMapper.selectStsDataDeptStatisticTop10List(stsDataDeptStatisticQuery);
    }

    @Transactional
    @Override
    public R<StsDataDetail> synData(EventNotificationAlert eventNotificationAlert) {
        Date date = null;
        Date startTime = null;
        if("timeRange".equals(eventNotificationAlert.getPeopleCounting().getStatisticalMethods())){
            startTime = eventNotificationAlert.getPeopleCounting().getTimeRange().getStartTime();
        }else  if("realTime".equals(eventNotificationAlert.getPeopleCounting().getStatisticalMethods())){
            startTime = eventNotificationAlert.getPeopleCounting().getRealTime().getTime();
        }else{
            throw new RuntimeException("时间格式不正确");
        }

        date = DateUtils.dateTime("yyyy-MM-dd HH", DateUtils.parseDateToStr("yyyy-MM-dd HH", startTime));
        String macAddress = eventNotificationAlert.getMacAddress();
        StsDevice stsDevice = stsDeviceService.selectStsDeviceByIdCode(eventNotificationAlert.getMacAddress());
        if(stsDevice == null){
            return R.fail("设备【" + macAddress + "】没有维护，请及时维护。");
        }

        StsDataDetail stsDataDetail = stsDataDetailMapper.lockByDate(stsDevice.getId(), date);
        if(stsDataDetail == null){
            stsDataDetail = new StsDataDetail();
        }

        if("timeRange".equals(eventNotificationAlert.getPeopleCounting().getStatisticalMethods())){
            /** 经过人数 */
            stsDataDetail.setPassNum(numAdd(eventNotificationAlert.getPeopleCounting().getPass(),stsDataDetail.getPassNum()));
            /** 进入人数 */
            stsDataDetail.setInNum(numAdd(eventNotificationAlert.getPeopleCounting().getEnter(),stsDataDetail.getInNum()));
            /** 离开人数 */
            stsDataDetail.setOutNum(numAdd(eventNotificationAlert.getPeopleCounting().getExit(),stsDataDetail.getOutNum()));
            if("1.0".equals(eventNotificationAlert.getVersion())){
                /** 重复人数 */
                stsDataDetail.setRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicatePeople(),stsDataDetail.getRepNum()));
            }else{
                /** 重复人数 */
                stsDataDetail.setRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicateEnter(),stsDataDetail.getRepNum()));
                stsDataDetail.setOutRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicateExit(),stsDataDetail.getOutRepNum()));
                stsDataDetail.setPassRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicatePass(),stsDataDetail.getPassRepNum()));
            }

            /** 儿童人数 */
            stsDataDetail.setChildNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "child"),stsDataDetail.getChildNum()));
            /** 少年人数 */
            stsDataDetail.setJuvenileNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "kid"),stsDataDetail.getJuvenileNum()));
            /** 青少年人数 */
            stsDataDetail.setTeenagerNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "teenager"),stsDataDetail.getTeenagerNum()));
            /** 青年人数 */
            stsDataDetail.setYouthNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "young"),stsDataDetail.getYouthNum()));
            /** 壮年人数 */
            stsDataDetail.setAdultNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "prime"),stsDataDetail.getAdultNum()));
            /** 中年人数 */
            stsDataDetail.setMiddleNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "middle"),stsDataDetail.getMiddleNum()));
            /** 中老年人数 */
            stsDataDetail.setElderlyNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "middleAged"),stsDataDetail.getElderlyNum()));
            /** 老年人数 */
            stsDataDetail.setSeniorNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "old"),stsDataDetail.getSeniorNum()));
            /** 未知年龄人数 */
            stsDataDetail.setUnknownAgeNum(numAdd(getValueCount(eventNotificationAlert.getAgeGroupList(), "unknown"),stsDataDetail.getUnknownAgeNum()));
            /** 男人数 */
            stsDataDetail.setManNum(numAdd(getValueCount(eventNotificationAlert.getGenderList(), "male"),stsDataDetail.getManNum()));
            /** 女人数 */
            stsDataDetail.setWomanNum(numAdd(getValueCount(eventNotificationAlert.getGenderList(), "female"),stsDataDetail.getWomanNum()));
            /** 未知性别人数 */
            stsDataDetail.setUnknownSexNum(numAdd(getValueCount(eventNotificationAlert.getGenderList(), "unknown"),stsDataDetail.getUnknownSexNum()));

        }else  if("realTime".equals(eventNotificationAlert.getPeopleCounting().getStatisticalMethods())){
            /** 经过人数 */
            stsDataDetail.setPassNum(eventNotificationAlert.getPeopleCounting().getPass());
            /** 进入人数 */
            stsDataDetail.setInNum(eventNotificationAlert.getPeopleCounting().getEnter());
            /** 离开人数 */
            stsDataDetail.setOutNum(eventNotificationAlert.getPeopleCounting().getExit());
            if("1.0".equals(eventNotificationAlert.getVersion())){
                /** 重复人数 */
                stsDataDetail.setRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicatePeople(),stsDataDetail.getRepNum()));
            }else{
                /** 重复人数 */
                stsDataDetail.setRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicateEnter(),stsDataDetail.getRepNum()));
                stsDataDetail.setOutRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicateExit(),stsDataDetail.getOutRepNum()));
                stsDataDetail.setPassRepNum(numAdd(eventNotificationAlert.getPeopleCounting().getDuplicatePass(),stsDataDetail.getPassRepNum()));
            }

            /** 儿童人数 */
            stsDataDetail.setChildNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "child"));
            /** 少年人数 */
            stsDataDetail.setJuvenileNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "kid"));
            /** 青少年人数 */
            stsDataDetail.setTeenagerNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "teenager"));
            /** 青年人数 */
            stsDataDetail.setYouthNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "young"));
            /** 壮年人数 */
            stsDataDetail.setAdultNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "prime"));
            /** 中年人数 */
            stsDataDetail.setMiddleNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "middle"));
            /** 中老年人数 */
            stsDataDetail.setElderlyNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "middleAged"));
            /** 老年人数 */
            stsDataDetail.setSeniorNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "old"));
            /** 未知年龄人数 */
            stsDataDetail.setUnknownAgeNum(getValueCount(eventNotificationAlert.getAgeGroupList(), "unknown"));
            /** 男人数 */
            stsDataDetail.setManNum(getValueCount(eventNotificationAlert.getGenderList(), "male"));
            /** 女人数 */
            stsDataDetail.setWomanNum(getValueCount(eventNotificationAlert.getGenderList(), "female"));
            /** 未知性别人数 */
            stsDataDetail.setUnknownSexNum(getValueCount(eventNotificationAlert.getGenderList(), "unknown"));

        }
        stsDataDetail.setDeviceId(stsDevice.getId());
        stsDataDetail.setDeviceName(stsDevice.getName());
        stsDataDetail.setDeptId1(stsDevice.getDeptId1());
        /** 一级部门名称 */
        stsDataDetail.setDeptName1(stsDevice.getDeptName1());
        /** 二级部门ID */
        stsDataDetail.setDeptId2(stsDevice.getDeptId2());
        /** 二级部门名称 */
        stsDataDetail.setDeptName2(stsDevice.getDeptName2());
        /** 三级部门ID */
        stsDataDetail.setDeptId3(stsDevice.getDeptId3());
        /** 三级部门名称 */
        stsDataDetail.setDeptName3(stsDevice.getDeptName3());
        /** 开始时间 */
        stsDataDetail.setStartTime(date);
        /** 结束时间 */
        stsDataDetail.setEndTime(DateUtils.addHours(date, 1));

        if(stsDataDetail.getId() != null){
            stsDataDetailMapper.updateStsDataDetail(stsDataDetail);
        }else{
            stsDataDetailMapper.insertStsDataDetail(stsDataDetail);
        }

        return R.ok(stsDataDetail);
    }

    private Integer numAdd(Integer num1, Integer num2){
        if(num1 == null){
            num1 = 0;
        }

        if(num2 == null){
            num2 = 0;
        }
        return num1 + num2;
    }

    private Integer getValueCount(List<EventNotificationAlert.ValueCount> valueCounts, String value){
        if(!CollectionUtils.isEmpty(valueCounts)){
            for(EventNotificationAlert.ValueCount valueCount:valueCounts){
                if(value.equals(valueCount.getValue())){
                    return valueCount.getCount();
                }
            }
        }

        return 0;
    }

    @Async
    @Override
    public void updateDeptName(Integer deptLevel, Long deptId, String deptName) {
        stsDataDetailMapper.updateDeptName(deptLevel, deptId,deptName);
    }

    @Override
    public List<StsDataDetail> selectStsWeekDataStatisticList(StsDataStatisticQuery stsDataStatisticQuery) {
        return stsDataDetailMapper.selectStsWeekDataStatisticList(stsDataStatisticQuery);
    }


    @Override
    public List<StsHolidayDataDetail> selectStsDataDeptStatisticHolidayList(String[] deptIds) {
        return stsDataDetailMapper.selectStsDataDeptStatisticHolidayList(deptIds);
    }
}
